package com.yanyilu.qiubite.util;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.yanyilu.qiubite.entity.Code;
import org.apache.catalina.mapper.Mapper;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by wo on 2018/8/22.
 */

public class SendMessageUtil {
    /**
     * 添加日志支持
     */
//    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(SendMessageUtils.class);

    //产品名称:云通信短信API产品,开发者无需替换
    static final String product = "Dysmsapi";
    //产品域名,开发者无需替换
    static final String domain = "dysmsapi.aliyuncs.com";
    // TODO 此处需要替换成开发者自己的AK(在阿里云访问控制台寻找) 记录下来的
//    static final String accessKeyId = "LTAIZoDQvkFhCx9m";
//    static final String accessKeySecret = "lfGKNHnOoASZNYUjI0WNqtJS79WFR1";
//    static final String accessKeyId = "LTAI4GEitE12GQ2MhnD5Fkqm";
    static final String accessKeyId = "LTAIZoDQvkFhCx9m";
//    static final String accessKeySecret = "LlYJ8ZOQU8CJlcyN2ccumg4dGJl0iQ";
    static final String accessKeySecret = "lfGKNHnOoASZNYUjI0WNqtJS79WFR1";
    static final int time = 300;
//    @Autowired
//    /**
//     * 发送短信
//     * @param models 短信模板变量对象
//     * @return
//     */
    public static Code sendMessage(String phoneNumber){
        Code codeEntity = new Code();
        codeEntity.setPhoneNumber(phoneNumber);
        String code = getCode();
        try{
            //解析传进的对象成json
            //Gson gson = new Gson();
            HashMap<String, Object> mapper = new HashMap<>();
            mapper.put("code",code);
            JSONObject json = new JSONObject(mapper);
            //可自助调整超时时间
            System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
            System.setProperty("sun.net.client.defaultReadTimeout", "10000");
            //初始化acsClient,暂不支持region化
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            //组装请求对象-具体描述见控制台-文档部分内容
            SendSmsRequest request = new SendSmsRequest();
            //必填:待发送手机号
            request.setPhoneNumbers(phoneNumber);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName("丘比特游玩");
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode("SMS_154505111");

            //request.setSignName("来闻");
            //必填:短信模板-可在短信控制台中找到
            //request.setTemplateCode("SMS_197897890");

            //request.setTemplateParam("{\"name\":\"123\"}");
//             可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
//            request.setTemplateParam("\"code\":\"180181\"}");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            request.setTemplateParam(json.toJSONString());
            //System.out.println("nm1:"+request.getTemplateParam());

            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            //request.setOutId("yourOutId");

            //hint 此处可能会抛出异常，注意catch
            SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
            //System.out.println("test:"+sendSmsResponse.getCode());

            //判断数据库里是否有该手机号

            if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
                //请求成功
                codeEntity.setCode(code);
                codeEntity.setEndTime((int)(System.currentTimeMillis()/1000)+time);
            }
            return codeEntity;
        } catch (ServerException e) {
            e.printStackTrace();
            return codeEntity;
        } catch (ClientException e) {
            e.printStackTrace();
            return codeEntity;
        }
    }


/*        public R confirm(@RequestParam Map<String,Object>reqMap){
        Code codeEntity = new Code();
        codeEntity = codeService.queryListByPhoneNumber(reqMap.get("phoneNumber").toString());
        if(codeEntity !=null){
            if((Integer.parseInt(String.valueOf(reqMap.get("code")))) == (codeEntity.getCode())){
                return R.ok().put("result","success").put("reason","手机号验证码正确");
            }else{
                return R.ok().put("result","fail").put("reason","验证码错误");
            }
        }else{
            return R.ok().put("result","fail").put("reason","手机号未注册");
        }
      }*/

      public static String  getCode() {
          String code = "";
          Random random = new Random();
          for (int i = 0; i < 6; i++) {
              int r = random.nextInt(10); //每次随机出一个数字（0-9）
              code = code + r;  //把每次随机出的数字拼在一起
          }
          return code;
      }
}
